# coding=utf-8
import os

from flask import Flask,flash,g,redirect,render_template,request,session,url_for
from flask.ext.login import current_user,login_required,login_user,logout_user,LoginManager
from flask.ext.openid import OpenID
from flask.ext.sqlalchemy import SQLAlchemy
from config import basedir
from forms import LoginForm
import models

# 填坑：不能使用 from models import User 导入 导入引用不了。。。。不知为啥。。。


app = Flask(__name__)
# 加载配置
app.config.from_object('config')
# 数据库
# 填坑：python2.7 使用pip 安装 SQLAlchemy 后运行报错 ImportError: No module named SQLAlchemy
# 使用pip install flask-SQLAlchemy安装 然后将导入包语句 import SQLAlchemy as SQLAlchemy 改为from flask.ext.sqlalchemy import SQLAlchemy
db = SQLAlchemy(app)


lm=LoginManager() # 得安装 flask-login扩展；     pip install flask-login
lm.init_app(app)
oid=OpenID(app,os.path.join(basedir,'tmp'))# 得安装flask-openid扩展 ；   pip install flask-openid

# 处理请求
@app.route('/')
@app.route("/index")
@login_required
def index():
    user=g.user
    posts=[
        {
            'author':{'nickname':'John'},
            'body':'John博文内容'
        },{
            'author': {'nickname': 'Susan'},
            'body': 'Susan博文内容'
        }
    ]
    # 使用Jinja2模板引擎
    return render_template('index.html',title='首页',user=user,posts=posts)
# 填坑： python2.7中使用Jinja2模板 有中文的时候要加 u ,例如下面的titl="注册" 程序会报错 应该改为 title=u"注册"
@app.route("/login",methods=['GET','POST'])
@oid.loginhandler
def login():
    if g.user is not None and g.user.is_authenticated():# 填坑：Flask-Login-0.4.0 会报错 TypeError: 'bool' object is not callable 改用 0.2.11
        return redirect(url_for('index'))
    form=LoginForm()
    if form.validate_on_submit():
        session['remenber_me']=form.remenber_me.data
        # flash('Login requested for OpenID="'+form.openid.data+'",remenber_me='+str(form.remenber_me.data))
        # return redirect('/index')
        return oid.try_login(form.openid.data,ask_for=['nickname','email'])
    return render_template('login.html',
                           title=u"登录",
                           form=form,
                           providers=app.config['OPENID_PROVIDERS'])
# 退出登录
@app.route('/logout')
def logout():
    logout_user()
    return redirect(url_for('index'))

@lm.user_loader
def load_user(id):
    return models.User.query.get(int(id))
@oid.after_login
def after_login(resp):
    if resp.email is None or resp.email=="":
        flash('请输入正确的邮箱地址！')
        return redirect(url_for('login'))
    user=models.User.query.filter_by(email=resp.email).first()
    if user is None :
        nickname=resp.nickname
        if nickname is None or nickname=="":
            nickname=resp.email.split('@')[0]
        user=models.User(nickname=nickname,email=resp.email)
        db.session.add(user)
        db.session.commit()
    remenber_me=False
    if 'remenber_me' in session:
        remenber_me=session['remenber_me']
        session.pop('remenber_me',None)
    login_user(user,remember=remenber_me)
    return redirect(request.args.get('next') or url_for('index'))
@app.before_request
def before_request():
    g.user=current_user





# 只能通过post方式访问
@app .route("/api",methods=["POST"])
def api():
    return 'This is a api!'

@app.route("/hello/")
@app.route("/hello/<username>")
def hello(username=None):
    # 处理变量
    return render_template("hello.html",title='欢迎',name=username)

if __name__ == '__main__':
    app.run()


